package repository;

import domain.Person;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.RepositoryDefinition;
import org.springframework.data.repository.query.Param;

import java.util.List;

/**
 * @program: springbootjpa-01
 * @description:
 * @author: Mr.Dai
 * @create: 2019-12-30 21:43
 **/
 //等同于 继承Repository
//@RepositoryDefinition(domainClass = Person.class,idClass = Integer.class)
public interface PersonRepository extends Repository<Person,Integer> {

    Person findPersonById(Integer id);

    // where lastname like "admin*";
    List<Person> findByLastNameLike(String lastName);

    Person findPersonByIdAndEmail(Integer id,String email);

    List<Person> findAllBy();

    // @query 查询
    @Query(value = "select p from Person p")
    List<Person> findAllPersons();

    @Query(value = "select p from Person  p where p.lastName like ?1")
    List<Person> findLikePerson(String lastName);

    @Query(value = "select p from Person  p where p.lastName like :lastName")
    List<Person> findLikePerson2(@Param("lastName") String lastName);

    @Query(value = "select * from person  p where p.last_name like ?1",nativeQuery = true)
    List<Person> findLikePerson3(String lastName);



    //可以通过自定义的 JPQL 完成 UPDATE 和 DELETE 操作. 注意: JPQL 不支持使用 INSERT
    //在 @Query 注解中编写 JPQL 语句, 但必须使用 @Modifying 进行修饰. 以通知 SpringData, 这是一个 UPDATE 或 DELETE 操作
    //UPDATE 或 DELETE 操作需要使用事务, 此时需要定义 Service 层. 在 Service 层的方法上添加事务操作.
    //默认情况下, SpringData 的每个方法上有事务, 但都是一个只读事务. 他们不能完成
    @Modifying
    @Query(value = "update Person p set p.email=?1 where p.id=?2 ")
    int updatePersonByEmail(String email,Integer id);

    @Modifying
    @Query(value = "delete from Person  p where p.id =?1")
    int deletePersonById(Integer id);
}
